package com.binguo.helper;


import com.alibaba.druid.support.json.JSONUtils;
import com.binguo.baidu.request.AddUserForm;
import com.binguo.baidu.request.UserInfo;
import com.binguo.baidu.response.AddUserVO;
import com.binguo.common.paymodel.MD5Util;
import com.binguo.common.util.JsonUtil;
import com.binguo.entity.face_local.AddFaceResultVO;
import com.binguo.entity.face_local.CreateFaceResultVO;
import com.binguo.entity.face_local.SearchFaceResultDetailVO;
import com.binguo.entity.face_local.SearchFaceResultVO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencentcloudapi.iai.v20180301.models.Candidate;
import com.tencentcloudapi.iai.v20180301.models.GetPersonBaseInfoResponse;
import com.tencentcloudapi.iai.v20180301.models.PersonInfo;
import com.tencentcloudapi.iai.v20180301.models.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

// 导入对应产品模块的client
// 导入要请求接口对应的request response类

@Service
public class BaiduFaceService {
    public static RestTemplate restTemplate = new RestTemplate();
    public static String ipAddress = "49.234.207.168";
    public static Gson gson = (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create();

    private static String pass = MD5Util.MD5Lower32("123456");

    private static Logger logger = LoggerFactory.getLogger(BaiduFaceService.class);

    public static HttpHeaders DEFAULT_JSON_HEADER_UTF8;
    static {
        DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean isShopExist(String shopId){

        return true;
    }

    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean createGroup(String shopId, String ipAddress){

        return true;
    }

    /**
     * 创建人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId 传shopId
     * @param customerId 传customerId
     * @param faceUrl 传人脸图片地址
     * @return faceId
     */
    public static String createPerson(String shopId, String customerId, String faceUrl, String ipAddress){
        try {
            AddUserForm addUserForm = new AddUserForm();
            addUserForm.setPass(pass);
            addUserForm.setImage_type("URL");
            addUserForm.setImage_content(faceUrl);
            addUserForm.setUser_id(customerId);
            addUserForm.setUser_info(new UserInfo());
            addUserForm.getUser_info().setName("jay2");
            addUserForm.getUser_info().setPhone_number("11111111111");
            addUserForm.setAction_type("APPEND");
            addUserForm.setQuality_control("NONE");

            String json = JsonUtil.toJson(addUserForm);
            logger.info("createPerson,request={}", json);
            HttpEntity requestBody = new HttpEntity(json, DEFAULT_JSON_HEADER_UTF8);

            ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/userManage/addUser", requestBody, String.class);
            String result = resp.getBody();

            logger.info("createPerson,result=" + result);
            AddUserVO addFaceResultVO = JsonUtil.parse(result, AddUserVO.class);
            if (addFaceResultVO.isCode()) {
                return System.currentTimeMillis() + "";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 删除人脸
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceId 传创建人脸时返回的faceId值
     * @return true:成功 false:失败
     */
    public static boolean deleteFace(String customerId, String faceId, String ipAddress){
        if (!customerId.contains("_")) {
            return false;
        }
        String shopId = customerId.split("_")[0];
        String customerIdPure = customerId.split("_")[1];
        MultiValueMap map = new LinkedMultiValueMap();


        map.add("shopId", shopId);
        map.add("customerId", customerIdPure);
        map.add("faceId", faceId);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("deleteFace,request=" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/delFace", requestBody, String.class);
        String result = resp.getBody();


        logger.info("deleteFace:" + result);

        AddFaceResultVO addFaceResultVO = null;
        try {
            addFaceResultVO = JsonUtil.parse(result, AddFaceResultVO.class);
            if (addFaceResultVO.getError() == 0) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 删除人员库
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @return true:成功 false:失败
     */
    public static boolean deleteGroup(String shopId, String ipAddress){


        return false;
    }

    /**
     * 删除人员(在不知道人员所属商户的情况下使用此方法)
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @return true:成功 false:失败
     */
    public static boolean deletePerson(String customerId, String ipAddress){

        if (!customerId.contains("_")) {
            return false;
        }
        String shopId = customerId.split("_")[0];
        String customerIdPure = customerId.split("_")[1];
        MultiValueMap map = new LinkedMultiValueMap();


        map.add("shopId", shopId);
        map.add("customerId", customerIdPure);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("deletePerson,request=" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/delPerson", requestBody, String.class);
        String result = resp.getBody();

        logger.info("deletePerson:" + result);

        AddFaceResultVO addFaceResultVO = null;
        try {
            addFaceResultVO = JsonUtil.parse(result, AddFaceResultVO.class);
            if (addFaceResultVO.getError() == 0) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 人员库删除人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param customerId
     * @return true:成功 false:失败
     */
    public static boolean deletePersonFromShop(String shopId, String customerId, String ipAddress){

        if (!customerId.contains("_")) {
            customerId = customerId.split("_")[1];
        }
        MultiValueMap map = new LinkedMultiValueMap();


        map.add("shopId", shopId);
        map.add("customerId", customerId);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("delPerson,request=" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/delPerson", requestBody, String.class);
        String result = resp.getBody();

        System.out.println(result);


        AddFaceResultVO addFaceResultVO = null;
        try {
            addFaceResultVO = JsonUtil.parse(result, AddFaceResultVO.class);
            if (addFaceResultVO.getError() == 0) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return false;
    }

    /**
     * 获取人员基础信息
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @return GetPersonBaseInfoResponse
     */
    public static GetPersonBaseInfoResponse getPersonBaseInfo(String customerId, String ipAddress){


        return null;
    }

    /**
     * 获取人员列表
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param offset 第几个结果集开始查
     * @param limit 查询多少个
     * @return faceId
     */
    public static PersonInfo[] getPersonList(String shopId, Integer offset, Integer limit, String ipAddress){

        return null;

    }

    /**
     * 人脸搜索
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromSingleShop(String faceUrl, String shopId, String ipAddress){
        return searchFacesFromMultiple(faceUrl, new String[]{shopId}, ipAddress);
    }

    /**
     * 人脸搜索
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromMultiple(String faceUrl, String[] shopId, String ipAddress){

        MultiValueMap map = new LinkedMultiValueMap();

        map.add("shopId", shopId[0]);
        map.add("filepath", faceUrl);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("searchFace,request=" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/searchFace", requestBody, String.class);
        String result = resp.getBody();

        try {
            SearchFaceResultVO addFaceResultVO = JsonUtil.parse(result, SearchFaceResultVO.class);
            if (addFaceResultVO.getError() == 0 && addFaceResultVO.getData().size() > 0) {
                Result[] results = new Result[1];

                SearchFaceResultDetailVO searchFaceResultDetailVO = (addFaceResultVO.getData().get(0));

                String customerId_faceId = searchFaceResultDetailVO.getLabel();

                String faceId = null;
                String customerId = null;
                String temp[] = customerId_faceId.split("_");
                if (temp.length == 3) {
                    faceId = temp[2];
                    customerId = temp[1];
                }else {
                    faceId = customerId_faceId.split("_")[1];
                    customerId = customerId_faceId.split("_")[0];
                }

                Result tempResult = new Result();

                Candidate candidate = new Candidate();
                candidate.setFaceId(faceId);
                candidate.setPersonId(shopId[0] + "_" + customerId);
                candidate.setScore(new Float(100));

                Candidate tempCandidate[] = new Candidate[1];
                tempCandidate[0] = candidate;
                tempResult.setCandidates(tempCandidate);
                results[0] = tempResult;
                return results;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 人脸检测与分析
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 人脸图片质量分
     */
    public static int detectFace(Integer shopId, String faceUrl, String ipAddress){

        MultiValueMap map = new LinkedMultiValueMap();

        map.add("filepath", faceUrl);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("detect face,request map==" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/detectFace", requestBody, String.class);
        String result = resp.getBody();

        logger.info("detect face==" + result);

        try {
            AddFaceResultVO addFaceResultVO = JsonUtil.parse(result, AddFaceResultVO.class);
            if (addFaceResultVO.getError() == 0) {
                return 100;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;

    }

    /**
     * 人脸比对
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrlSource
     * @param faceUrlTarget
     * @return 对比分数
     */
    public static float compareFace(String faceUrlSource, String faceUrlTarget, String ipAddress){

        return 0;

    }

    /**
     * 人脸静态活体检测
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 检测结果分数
     */
    public static float detectLiveFace(String faceUrl, String ipAddress){



        return 0;
    }

    /**
     * 人脸验证
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceUrl
     * @return true:匹配 false:不匹配
     */
    public static boolean VerifyFace(String customerId, String faceUrl, String ipAddress){

        return false;

    }

    /**
     * 增加人脸
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceUrl
     * @return true:成功 false:失败
     */
    public static String addFace(String customerId, String faceUrl, String ipAddress){
        if (!customerId.contains("_")) {
            return null;
        }
        String shopId = customerId.split("_")[0];
        String customerIdPure = customerId.split("_")[1];

        MultiValueMap map = new LinkedMultiValueMap();

        map.add("shopId", shopId);
        map.add("customerId", customerIdPure);
        map.add("filepath", faceUrl);

        logger.info("addface,request=" + JSONUtils.toJSONString(map));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(map, headers);
        logger.info("addFace,request map==" + map);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://" + ipAddress + "/addFace", requestBody, String.class);
        String result = resp.getBody();


        logger.info("addface,result=" + result);

        try {
            CreateFaceResultVO addFaceResultVO = JsonUtil.parse(result, CreateFaceResultVO.class);
            if (addFaceResultVO.getError() == 0 && addFaceResultVO.getData().size() > 0) {
                return (addFaceResultVO.getData().get(0)).getFaceid();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }


    public static void main(String[] args) {
        String s = "a_b_c";
        System.out.println(s.split("_").length);
    }

}
